import {
	getOssApkInfo,
	getOssImgInfo
} from '../api/application'


function dataURLtoBlob(dataurl) { //Base64 to Blob
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

/* 上传函数 */
export function ossImage(path) {
	return new Promise((resolve, reject) => {
		let id = 2
		getOssImgInfo({
			userId: id
		}).then(res => { //获取签名
			let data = res.data
			let date = new Date;
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let stroeAs = "miniPro/" + year + "-" + month + "/" + Date.parse(new Date()) + parseInt(Math.random() * (100000 - 10000 + 1) + 10000, 10) + ".jpg"
			uni.uploadFile({
				url: data.host,
				filePath: path,
				name: 'file',
				formData: {
					'key': stroeAs,
					'policy': data.policyBase64,
					'OSSAccessKeyId': data.accessid,
					'signature': data.signature,
					'success_action_status': '200'
				},
				success: (res) => {
					// console.log("上传成功", data.host + '/' + stroeAs)
					resolve(data.host + '/' + stroeAs)
				},
				fail: (err) => {
					console.log('上传失败', err);
					reject(err)
				}
			})

		}).catch(err => {
			reject(err)
		})
	})
}


export function ossUploadApk(name, path, size) {
	return new Promise((resolve, reject) => {
		let id = 1
		getOssApkInfo({
			userId: id
		}).then(res => { //获取签名
			let data = res.data
			console.log(data)
			let date = new Date;
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let stroeAs = "miniPro/" + year + "-" + month + "/"  + name
			uni.uploadFile({
				url: data.host,
				filePath: path,
				name: 'file',
				formData: {
					'key': stroeAs,
					'policy': data.policyBase64,
					'OSSAccessKeyId': data.accessid,
					'signature': data.signature,
					'success_action_status': '200'
				},
				success: (res) => {
					resolve(data.host + '/' + stroeAs)
				},
				fail: (err) => {
					console.log('上传失败', err);
					reject(err)
				}
			})

		}).catch(err => {
			reject(err)
		})
	})
}